package com.probox.apiModules.controller.platfom;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.probox.common.core.domain.R;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.UEditorConfigUitl;
import com.probox.common.core.utils.UEditorConfigVo;
import com.probox.common.core.utils.file.FileUtils;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.service.file.ISysFileService;
import com.probox.common.entity.utils.QiniuAdapter;
import com.probox.common.entity.vo.file.UploadResultVo;
import com.probox.systemApi.domain.SysFile;
import com.probox.systemApi.domain.UploadFile;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 文件请求处理
 *
 * @author usoft
 */
@RestController
@RequestMapping("/file")
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private QiniuAdapter qiniuAdapter;


    @PostMapping("/upload/share")
    public R<String> getUploadUrl(@RequestBody UploadFile uploadFile) {
        String s = qiniuAdapter.upFileToQiNiu(uploadFile.getPath(), uploadFile.getSuffixName(), uploadFile.getData());
        return R.ok(qiniuAdapter.getDomain() + s);
    }

    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public R<SysFile> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取七牛云文件上传Token
     */
    @GetMapping("/getUploadToken")
    public R<UploadResultVo> getUploadToken() {
        try {
            return R.ok(qiniuAdapter.getUploadToken());
        } catch (Exception e) {
            log.error("获取Tockert失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取七牛云文件上传Token
     */
    @GetMapping("/getVideoUpToken")
    public R<UploadResultVo> getVideoUpToken() {
        try {
            return R.ok(qiniuAdapter.getVideoUpToken());
        } catch (Exception e) {
            log.error("获取Tockert失败", e);
            return R.fail(e.getMessage());
        }
    }

    @RequestMapping("/ueditor")
    public AjaxResult imageAction(String action,HttpServletRequest request){
        AjaxResult ajaxResult = new AjaxResult();
        if(action.equals("config")){//初始化参数配置：imagePathFormat、imageUrlPrefix
            UEditorConfigVo vo = new UEditorConfigVo();
            String s = JSON.toJSONString(vo);
            JSONObject jsonConfig= JSON.parseObject(s);
            Set<String> setList = jsonConfig.keySet();
            Iterator<String> it = setList.iterator();
            try {
                while(it.hasNext()){
                    String key= (String) it.next().toString();
                    Object jsonobj=jsonConfig.get(key);
                    if(jsonobj instanceof JSONArray){
                        JSONArray jsonArr = (JSONArray)jsonConfig.get(key);
                        int l=jsonArr.size();
                        String[] str = new String[l];
                        for (int i = 0; i < l; i++){
                            str[i] =jsonArr.getString(i);
                        }
                        ajaxResult.put(key,str);
                    }else{
                        ajaxResult.put(key,jsonConfig.get(key));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else if("imageActionName".equals(action)){//上传图片
//			HttpServletResponse response=ResponseUtils.getResponse(surestream);
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new BaseException( "Request is not multipart, please 'multipart/form-data' enctype for your form" );
            }
            String state="SUCCESS";
            String url="";
            String title="";
            try{
                MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
                for (Iterator<String> it = fileRequest.getFileNames(); it.hasNext();) {
                    String key = (String) it.next();
                    MultipartFile multipartFile = fileRequest.getFile(key);
                    Map<String, Object> mapobj=UEditorConfigUitl.getConfig(UEditorConfigUitl.imageAction);
                    Long imageMaxSize=(Long)mapobj.get("imageMaxSize");//允许上传的文件最大值
                    String[] strAllows= (String[])mapobj.get("imageAllowFiles");//允许上传类型
                    List<String> allowTypes= Arrays.asList(strAllows);
                    String filesuffix=UEditorConfigUitl.getFileSuffix(multipartFile.getOriginalFilename());//获取上传文件的后缀名
                    long fileSize=multipartFile.getSize();

                    if(!ObjectUtil.isEmpty(imageMaxSize)){
                        if(fileSize >imageMaxSize.longValue() ){
                            throw new BaseException("上传图片已超过允许的最大值，最大值为["+ imageMaxSize+"]");
                        }
                    }
                    if(!allowTypes.contains(filesuffix.toLowerCase())){
                        throw new BaseException("["+ filesuffix+"]类型文件不允许上传");
                    }
                    String filename=multipartFile.getOriginalFilename();
                    //修改上传文件名
                    if(!ObjectUtil.isEmpty(filename)){
                        filename=DateUtil.date()+"_"+multipartFile.getOriginalFilename();
                    }
                    url=qiniuAdapter.uploadInputStream(filename, multipartFile.getInputStream(),null);

                }
            } catch (Exception e){
                state="FAILURE";
                e.printStackTrace();
            }
            ajaxResult.put("state", state);
            ajaxResult.put("url", url);
            ajaxResult.put("title", title);
            ajaxResult.put("original", title);
        }

        return ajaxResult;

    }


}
